package breadbox.client.logging;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import breadbox.client.files.Chunk;

/**
 * Client-side logging 
 * @author Forrest
 *
 */
public class Logger implements Log {
	private File dir;
	
	/**
	 * Construct a new Logger instance
	 */
	public Logger() {
		// check if the log directory exists, create if necessary
		dir = new File(LOG_DIRECTORY);
		if (!dir.exists()) {
			dir.mkdir();
		}
	}
	
	/**
	 * List the files currently in the log
	 * @return List<String> list of filenames
	 */
	public List<String> list() {
		List<String> filenames = new ArrayList<String>();
		File[] files = dir.listFiles();
		for (File f : files) {
			filenames.add(f.getName());
		}
		return filenames;
	}

	/**
	 * Return a list of the Chunks in the log for a filename
	 * @return List<Chunk> list of LogChunks
	 * @throws FileNotFoundException 
	 */
	public List<LogChunk> read(String filename) throws FileNotFoundException {
		LogFileInput fileIn = new LogFileInput(filename);
		List<LogChunk> chunks = null;
		try {
			chunks = fileIn.readAllChunks();
			fileIn.close();
		} catch (IOException e) {
			System.err.println("Log error: Cannot read data from log");
		}
		return chunks;
	}

	/**
	 * Write a list of chunks to the log
	 */
	public void writeChunks(List<Chunk> chunks, boolean compression) throws IOException {
		LogFileOutput fileOut = new LogFileOutput(chunks.get(0).getFilename());
		for (Chunk k : chunks) {
			LogChunk l = new LogChunk(k, compression);
			fileOut.writeChunk(l);
		}
		fileOut.close();
	}

	/**
	 * Get a list of the ids for a filename
	 * @param filename String
	 * @return long[] list of ids
	 */
	public long[] getIds(String filename) throws FileNotFoundException {
		List<LogChunk> chunks = read(filename);
		int max = chunks.size();
		long[] result = new long[max];
		for (int i = 0; i < max; i++) {
			result[i] = chunks.get(i).getID();
		}
		return result;
	}

	/**
	 * Remove the log file for a given filename
	 * @param filename String
	 */
	public void remove(String filename) {
		File f = new File(Log.LOG_DIRECTORY + "/" + filename + Log.LOG_FILE_EXTENSION);
		f.delete();
	}

	/**
	 * Determine if the current file is compressed or not
	 * @param filename String
	 * @return boolean compression status
	 * @throws FileNotFoundException
	 */
	public boolean getCompression(String filename) throws FileNotFoundException {
		List<LogChunk> chunks = read(filename);
		return chunks.get(0).getCompression();
	}

	public boolean exists(String filename) {
		File f = new File(Log.LOG_DIRECTORY + "/" + filename + Log.LOG_FILE_EXTENSION);
		return f.exists();
	}
}
